package org.hjj.design.u95.reporter;

import org.hjj.design.u95.Aggregator;
import org.hjj.design.u95.domain.RequestInfo;
import org.hjj.design.u95.domain.RequestStat;
import org.hjj.design.u95.storage.MetricsStorage;
import org.hjj.design.u95.viewer.StatViewer;

import java.util.List;
import java.util.Map;

/**
 * abstract class of based reporter
 *
 * @author:何嘉俊
 * @date:2021/5/18
 */
public abstract class ScheduledReporter {
    protected MetricsStorage metricsStorage;
    protected Aggregator aggregator;
    protected StatViewer viewer;

    public ScheduledReporter(MetricsStorage metricsStorage, Aggregator aggregator, StatViewer viewer) {
        this.metricsStorage = metricsStorage;
        this.aggregator = aggregator;
        this.viewer = viewer;
    }

    protected void doStatAndReport(long startTimeInMillis, long endTimeInMillis) {
        long durationInMillis = endTimeInMillis - startTimeInMillis;
        Map<String, List<RequestInfo>> requestInfos = metricsStorage.getRequestInfos(startTimeInMillis, endTimeInMillis);
        Map<String, RequestStat> requestStats = aggregator.aggregate(requestInfos, durationInMillis);
        viewer.output(requestStats, startTimeInMillis, endTimeInMillis);
    }
}
